/**
 * Created by mrcode on 2016/3/26.
 * 必须依赖文件：
 *  1. bootstrap.min.css
 *  3. poplayer.css
 *  4. jquery.min.js
 *  5. poplayer.js
 * 可选：
 *  1. animate.css 动画效果
 *  2. font-awesome icon图标支持
 * 最简单入门：直接new
 */
function poplayer(params) {
    if (!params) {
        throw new error("初始化参数必选");
    }
    var me = this;
    initContainer();

    this.title = params.title;
    /**
     * 展示内容：可以是文字，可以是html代码等
     */
    this.content = params.content;
    /**
     *  按钮数组：
     *  btn类型:{ text: 'Info', style: 'info',action:}
     *  btn类型：
     *  按钮通用属性：1. text:按钮标题，style：按钮样式，action：按钮回掉函数，返回true,才会关闭窗体
     */
    this.buttons = params.buttons;
    this.dialog = params.dialog;
    this.onConfirm = params.onConfirm;
    this.onCancel = params.onCancel;
    /**
     * default : 左右居中，top20%
     * center : 居中
     */
    this.position = params.position;
    /**
     * awesome 图标,class名称可以组合，如动态旋转的星星icon-star icon-spin
     * */
    this.icon = params.icon;
    /** 进入效果 */
    this.animateEntrance = params.animateEntrance;
    /** 退出效果 */
    this.animateClosing = params.animateClosing;
    /** 对外暴露的程序出发关闭弹窗方法 */
    this.api_close = function () {
        api_close();
    };
    /** 是否自动关闭窗体 */
    this.autoclose = params.autoclose;
    /** 是否自动关闭窗体:超时 默认2秒(2000毫秒)*/
    this.timeout = params.timeout;

    handerIcon();
    handerTitle();
    handerContent();
    handerToolbar();
    if (this.position == "center") {
        centerModals(me.ass_container);
        hs(me.ass_container);
    }
    api_open();
    handerAutoclose();


    //大容器
    function initContainer() {
        var $container = createTag("div");
        $container.addClass("poplayer-container modal center shown");
        me.ass_container = $container;
        initOverlay();
        initFixer();
    }

    //遮罩层
    function initOverlay() {
        var $overlay = createTag("div");
        $overlay.addClass("poplayer-overlay");
        me.ass_container.append($overlay);
        me.ass_overlay = $overlay;
    }

    //内容层外层容器
    function initFixer() {
        var $fixer = createTag("div");
        $fixer.addClass("poplayer-fixer");
        me.ass_container.append($fixer);
        me.ass_fixer = $fixer;
        initOuter();
    }

    //内容层里层容器
    function initOuter() {
        var $outer = createTag("div");
        $outer.addClass("poplayer-outer");
        me.ass_fixer.append($outer);
        me.ass_outer = $outer;
        initOuter_content();
        initToolbar();
    }

    //内容展示层容器
    function initOuter_content() {
        var $outer_content = createTag("div");
        $outer_content.addClass("poplayer-content");
        me.ass_outer.append($outer_content);
        me.ass_outer_content = $outer_content;

        initIcon();
        initTitle();
        initMessage();
    }

    //工具按钮容器
    function initToolbar() {
        var $toolbar = createTag("div");
        $toolbar.addClass("poplayer-toolbar inline");
        me.ass_outer.append($toolbar);
        me.ass_toolbar = $toolbar;
    }

    //标题容器
    function initTitle() {
        var $title = createTag("h1");
        $title.addClass("poplayer-title");
        me.ass_outer_content.append($title);
        me.ass_title = $title;
    }

    //内容容器
    function initMessage() {
        var $message = createTag("div");
        $message.addClass("poplayer-message");
        me.ass_outer_content.append($message);
        me.ass_outer_message = $message;
    }

    //图标容器
    function initIcon() {
        var $icon = createTag("span");
        me.ass_outer_content.append($icon);
        me.ass_outer_icon = $icon;
    }

    //处理图标
    function handerIcon() {
        var icon = params.icon;
        if (icon) {
            me.ass_outer_icon.addClass(icon);
        }
    }

    //处理标题
    function handerTitle() {
        var title = params.title;
        if (title) {
            me.ass_title.text(title);
        }
    }

    //处理内容
    function handerContent() {
        var content = params.content;
        if (content) {
            me.ass_outer_message.html(content);
        }else{
            me.ass_outer_message.html(params);
        }
    }

    function handerToolbar() {
        var dialog = me.dialog;
        var buttons = me.buttons;
        if ("confirm" == dialog) {
            handerToolbar_confirm();
        }else if(buttons){
            handerToolbar_buttons();
        }
    }

    function handerToolbar_confirm() {
        var onConfirm = params.onConfirm;
        var onCancel = params.onCancel;
        if (onConfirm) {
            var style = (onConfirm.style ? onConfirm.style : "danger");
            $btn = newBtn(style);
            me.ass_toolbar.append($btn);
            var text = (onConfirm.text ? onConfirm.text : "Confirm");
            $btn.text(text);
            $btn.on("click", function () {
                var action = onConfirm.action;
                if (action) {
                    if (action.call(me)) {
                        api_close();
                    }
                } else {
                    api_close();
                }
            });
        }
        if (onCancel) {
            var style = (onCancel.style ? onCancel.style : "default");
            $btn = newBtn(style);
            me.ass_toolbar.append($btn);
            var text = (onCancel.text ? onCancel.text : "Concel");
            $btn.text(text);
            $btn.on("click", function () {
                var action = onCancel.action;
                if (action) {
                    if (action.call(me)) {
                        api_close();
                    }
                } else {
                    api_close();
                }
            });
        }
    }
    /** 处理多按钮：Multiple Buttons */
    function handerToolbar_buttons(){
        var buttons = me.buttons;
        var primary = buttons.primary;
        var success = buttons.success;
        var info = buttons.info;
        var danger = buttons.danger;
        var close = buttons.close;
        if(primary){
            addBtn(primary,"primary","primary");
        }
        if(success){
            addBtn(success,"success","success");
        }
        if(info){
            addBtn(info,"info","info");
        }
        if(danger){
            addBtn(danger,"danger","danger");
        }
        if(close){
            addBtn(close,"close","close");
        }
    }

    /**
     *  添加按钮，最常用的添加按钮方法
     * @param btnParams 参数
     * @param defStyle 默认样式
     * @param defText 默认文字
     * @param defAction 默认处理
     */
    function addBtn(btnParams,defStyle,defText,defAction){
        var style = (btnParams.style ? btnParams.style : defStyle);
        $btn = newBtn(style);
        me.ass_toolbar.append($btn);
        var text = (btnParams.text ? btnParams.text : defText);
        $btn.text(text);
        $btn.on("click", function () {
            var action = (btnParams.action?btnParams.action:defAction);
            if (action) {
                if (action.call(me)) {
                    api_close();
                }
            } else {
                api_close();
            }
        });
    }

    /** 打开窗体 */
    function api_open() {
        var animateEntrance = params.animateEntrance;
        $("body").append(me.ass_container);
        if (animateEntrance) {
            addAni(me.ass_outer, animateEntrance);
        } else {
            addAni(me.ass_outer, "fadeIn");
        }
    };
    /** 关闭弹窗 */
    function api_close() {
        var animateClosing = params.animateClosing;
        var aniName;
        if (animateClosing) {
            aniName = animateClosing;
        } else {
            aniName = "fadeOut";
        }
        addAni(me.ass_container, "fadeOut");
        addAni(me.ass_fixer, aniName, function () {
            me.ass_container.remove();
        });
    }

    /** 自动关闭窗体 */
    function handerAutoclose(){
        var autoclose = params.autoclose;
        var timeout = params.timeout;
        if(autoclose){
            if(!timeout){
                timeout = 2000;
            }
            window.setTimeout(function(){
                api_close();
            },timeout);
        }

    }

    function newBtn(style) {
        var $btn = createTag("a");
        $btn.attr("href", "javascript:void(0)");
        $btn.addClass("poplayer-button");
        if (style) {
            $btn.addClass(style);
        }
        return $btn;
    }

    /**
     * 绝对垂直居中
     * @param target
     */
    function centerModals(target) {
        $(target).each(function (i) {
            var $clone = $(this).clone().css('display', 'block').appendTo('body');
            var top = Math.round(($clone.height() - $clone.find('.poplayer-fixer').height()) / 2);
            top = top > 0 ? top : 0;
            $clone.remove();
            $(this).find('.poplayer-fixer').css("margin-top", top);
        });
    }

    /*判断手机横竖屏状态：*/
    function hengshuping() {
        if (window.orientation == 180 || window.orientation == 0) {
            centerModals(me.ass_container);
        }
        if (window.orientation == 90 || window.orientation == -90) {
            centerModals(me.ass_container);
        }
    }

    function hs() {
        window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
    }

    return this;
}

/**
 * 添加动态效果，
 * @param target 目标窗体jquery对象
 * @param aniName animated 中的效果名称
 * @param fun 效果执行完成后，需要执行的方法
 */
function addAni(target, aniName, fun) {
    target.addClass(aniName + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
        $(this).removeClass(aniName + ' animated');
        if (fun) {
            fun();
        }
    });
}
/**
 * 创建标签元素
 * @param name
 */
function createTag(name) {
    return $("<" + name + "></" + name + ">");
}





